
<!-- 
 @Author: LW  
 @Date: 2021-01-15 14:24:47  
 @function: 文件上传 
 ---------------------------------------------------------- 
 -->
<template>
  <div class="upload"></div>
</template>
<script>
import $ from "jquery";
import WebUploader from "webuploader";
export default {
  name: "vue-upload",
  props: {
    //fileType: null, //文件类型
    //file: null,
    //folderPath: "WaterSoilProjectVectorgraph",
    //accept:"zip"
    //fileNumLimit
    uploadInfo: {
      type: Object,
      default: null,
    },
    // 上传地址
    url: {
      type: String,
      default: "",
    },
    // //上传最大数量 默认为100
    // fileNumLimit: {
    //   type: Number,
    //   default: 100,
    // },
    //大小限制 默认2M
    fileSingleSizeLimit: {
      type: Number,
      default: 2048000,
    },
    //上传时传给后端的参数，一般为token，key等
    formData: {
      type: Object,
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    //上传按钮ID
    uploadButton: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploader: null,
    };
  },
  mounted() {
    this.initWebUpload();
  },
  methods: {
    initWebUpload() {
      let self = this;
      this.uploader = WebUploader.create({
        auto: true, //选完文件后，是否自动上传
        swf: "/webuploader/Uploader.swf", //swf文件路径
        server: self.$store.getters.fileServerURI + "/api/Files/SaveFiles", // 文件接收服务端
        pick: {
          id: this.uploadButton, // 选择文件的按钮
          multiple: this.multiple, // 是否多文件上传 默认false
          label: "",
        },
        accept: this.getAccept(this.uploadInfo.accept), //允许选择文件格式。
        threads: 3,
        fileNumLimit: this.uploadInfo.fileNumLimit, // 限制上传个数
        //fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制单个上传图片的大小
        formData: this.formData, // 上传所需参数
        chunked: true, //分片上传
        chunkSize: 1024 * 1024 * 10, //分片大小
        duplicate: true, // 重复上传
      });
      // 当有文件被添加进队列的时候，添加到页面预览
      this.uploader.on("fileQueued", (file) => {
        file.source.ruid = self.uuid();
        self.$emit("fileChange", file);
      });
      this.uploader.on("uploadBeforeSend", (file, data) => {
        data.guid = file.file.source.ruid;
        data.servicePath = self.uploadInfo.servicePath;
        data.folderPath = self.uploadInfo.folderPath;
      });
      // 文件上传过程中创建进度条实时显示。
      this.uploader.on("uploadProgress", (file, percentage) => {
        self.$emit("progress", file, percentage);
      });
      this.uploader.on("uploadSuccess", (file, response) => {
        self.$emit("success", file, response);
      });
      this.uploader.on("uploadError", (file, reason) => {
        console.error(reason);
        self.$emit("uploadError", file, reason);
      });
      this.uploader.on("error", (type) => {
        let errorMessage = "";
        if (type === "F_EXCEED_SIZE") {
          errorMessage = `文件大小不能超过${
            self.fileSingleSizeLimit / (1024 * 1000)
          }M`;
        } else if (type === "Q_EXCEED_NUM_LIMIT") {
          errorMessage = "文件上传已达到最大上限数";
        } else {
          errorMessage = `上传出错！请检查后重新上传！错误代码${type}`;
        }
        console.error(errorMessage);
        self.$emit("error", errorMessage);
      });
      this.uploader.on("uploadComplete", (file, response) => {
        self.$emit("complete", file, response);
      });
    },
    upload(file) {
      this.uploader.upload(file);
    },
    stop(file) {
      this.uploader.stop(file);
    },
    // 取消并中断文件上传
    cancelFile(file) {
      this.uploader.cancelFile(file);
    },
    // 在队列中移除文件
    removeFile(file, bool) {
      this.uploader.removeFile(file, bool);
    },
    //限制上传格式
    getAccept(accept) {
      switch (accept) {
        case "text":
          return {
            title: "Texts",
            exteensions: "doc,docx,xls,xlsx,ppt,pptx,pdf,txt",
            mimeTypes: ".doc,docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt",
          };
          break;
        case "media":
          return {
            title: "Medias",
            exteensions: "mp4,gif,jpg,jpeg,bmp,png",
            mimeTypes: ".mp4,.gif,.jpg,.jpeg,.bmp,.png",
          };
          break;
        case "video":
          return {
            title: "Videos",
            exteensions: "mp4",
            mimeTypes: ".mp4",
          };
          break;
        case "image":
          return {
            title: "Images",
            exteensions: "gif,jpg,jpeg,bmp,png",
            mimeTypes: ".gif,.jpg,.jpeg,.bmp,.png",
          };
          break;
        case "zip":
          return {
            title: "zips",
            exteensions: "zip",
            mimeTypes: ".zip",
          };
          break;
        default:
          return accept;
      }
    },
    //获取uuid-32
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; //bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      //s[8] = s[13] = s[18] = s[23] = "-";
      var uuid = s.join("");
      return uuid;
    },
  },
};
</script>

<style lang="scss">
.webuploader-container {
  position: relative;
}
.webuploader-element-invisible {
  position: absolute !important;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px, 1px, 1px, 1px);
}
.webuploader-pick {
  position: relative;
  display: inline-block;
  cursor: pointer;
  background: #00b7ee;
  padding: 10px 15px;
  color: #fff;
  text-align: center;
  border-radius: 3px;
  overflow: hidden;
}
.webuploader-pick-hover {
  background: #00a2d4;
}
.webuploader-pick-disable {
  opacity: 0.6;
  pointer-events: none;
}
</style>
